#!/usr/bin/env python3
"""
富途牛牛监控 - 股票跟单软件
主程序入口

使用方法:
    python main.py

确保在运行前安装所需依赖:
    pip install -r requirements.txt

启动OCR服务:
    rapidocr_api
"""

import sys
import os
import logging
import socket
import subprocess
import time

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

from utils.logger import LoggerManager
from gui.main_window import main as gui_main


def check_dependencies():
    """检查必要的依赖包"""
    print("🔍 检查依赖包...")
    
    required_packages = [
        ('PyQt5', 'PyQt5'),
        ('pillow', 'PIL'),
        ('requests', 'requests')
    ]
    
    missing_packages = []
    
    for package_name, import_name in required_packages:
        try:
            __import__(import_name)
            print(f"✅ {package_name} 已安装")
        except ImportError:
            missing_packages.append(package_name)
            print(f"❌ {package_name} 未安装")
    
    if missing_packages:
        print("\n缺少必要的依赖包:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements_clean.txt")
        print("或运行: 安装依赖.bat")
        return False
    
    return True


def fix_qt_plugin_path():
    """修复Qt平台插件路径问题（虚拟环境常见问题）"""
    try:
        import PyQt5
        
        # 设置Qt平台插件环境变量
        qt_plugin_path = os.path.join(os.path.dirname(PyQt5.__file__), 'Qt', 'plugins')
        if os.path.exists(qt_plugin_path):
            os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = qt_plugin_path
            print(f"🔧 设置Qt插件路径: {qt_plugin_path}")
        
        # 尝试其他可能的路径
        possible_paths = [
            os.path.join(os.path.dirname(PyQt5.__file__), 'Qt5', 'plugins'),
            os.path.join(sys.prefix, 'Lib', 'site-packages', 'PyQt5', 'Qt', 'plugins'),
            os.path.join(sys.prefix, 'Lib', 'site-packages', 'PyQt5', 'Qt5', 'plugins')
        ]
        
        for path in possible_paths:
            if os.path.exists(path) and 'QT_QPA_PLATFORM_PLUGIN_PATH' not in os.environ:
                os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = path
                print(f"🔧 设置Qt插件路径: {path}")
                break
                
        return True
        
    except Exception as e:
        print(f"⚠️ Qt插件路径修复失败: {e}")
        return False

def check_environment():
    """检查运行环境"""
    print("🔍 检查运行环境...")
    
    # 检查Python版本
    python_version = sys.version_info
    if python_version < (3, 6):
        print(f"❌ Python版本过低: {python_version.major}.{python_version.minor}")
        print("需要Python 3.6或更高版本")
        return False
    
    print(f"✅ Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    # 检查依赖包
    if not check_dependencies():
        return False
    
    # 修复Qt平台插件路径问题
    fix_qt_plugin_path()
    
    # 检查项目目录结构
    required_dirs = ['gui', 'ocr', 'utils', 'config', 'images', 'logs', 'ocr_results']
    for dir_name in required_dirs:
        dir_path = os.path.join(project_root, dir_name)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path, exist_ok=True)
            print(f"📁 创建目录: {dir_name}")
    
    print("✅ 项目目录结构检查完成")
    
    return True


def check_port_availability(port):
    """检查端口是否可用"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.settimeout(1)
            result = sock.connect_ex(('127.0.0.1', port))
            return result != 0  # 返回True表示端口可用
    except Exception:
        return True  # 出错时假设端口可用


def start_ocr_service():
    """启动OCR服务"""
    print("🚀 尝试启动OCR服务...")
    
    # 检查9003端口是否被占用
    if not check_port_availability(9003):
        print("✅ 端口9003已被占用，OCR服务可能已启动")
        return True
    
    # 查找ocr.exe文件
    ocr_exe_path = os.path.join(project_root, "ocr.exe")
    
    if not os.path.exists(ocr_exe_path):
        print(f"⚠️ 未找到OCR服务文件: {ocr_exe_path}")
        print("🔍 将尝试使用系统已安装的OCR服务")
        return False
    
    try:
        print(f"🎯 启动OCR服务: {ocr_exe_path}")
        
        # 启动OCR服务（后台运行，不显示命令行窗口）
        if os.name == 'nt':  # Windows系统
            subprocess.Popen(
                [ocr_exe_path],
                creationflags=subprocess.CREATE_NO_WINDOW,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL
            )
        else:  # Linux/Mac系统
            subprocess.Popen(
                [ocr_exe_path],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL
            )
        
        # 等待OCR服务启动
        print("⏳ 等待OCR服务启动...")
        for i in range(10):  # 最多等待10秒
            time.sleep(1)
            if not check_port_availability(9003):  # 端口被占用，说明服务启动了
                print(f"✅ OCR服务启动成功！(耗时{i+1}秒)")
                return True
        
        print("⚠️ OCR服务启动超时，但已在后台运行")
        return False
        
    except Exception as e:
        print(f"❌ 启动OCR服务失败: {e}")
        return False


def check_ocr_service():
    """检查OCR服务状态"""
    print("🔍 检查OCR服务...")
    
    try:
        import requests
        response = requests.get("http://127.0.0.1:9003/docs", timeout=5)
        if response.status_code == 200:
            print("✅ OCR服务运行正常")
            return True
    except requests.exceptions.ConnectionError:
        print("⚠️ OCR服务未启动")
        return False
    except Exception as e:
        print(f"❌ OCR服务检查失败: {e}")
        return False


def initialize_logging():
    """初始化日志系统"""
    try:
        logger_manager = LoggerManager()
        logger = logger_manager.get_logger(__name__)
        logger.info("=" * 60)
        logger.info("富途牛牛监控软件启动")
        logger.info(f"Python版本: {sys.version}")
        logger.info(f"工作目录: {os.getcwd()}")
        logger.info(f"项目根目录: {project_root}")
        logger.info("=" * 60)
        return True
    except Exception as e:
        print(f"❌ 日志系统初始化失败: {e}")
        return False


def show_startup_info():
    """显示启动信息"""
    print("\n" + "=" * 60)
    print("🎯 富途牛牛监控 - 股票跟单软件")
    print("=" * 60)
    print("版本: 1.0.0")
    print("开发时间: 2024-12")
    print("")
    print("功能特性:")
    print("• OCR文字识别监控")
    print("• 可视化区域框选")
    print("• 实时截图预览")
    print("• 自动交易信号识别")
    print("• 详细运行日志")
    print("• 操作历史记录")
    print("")
    print("使用说明:")
    print("1. 程序将自动启动OCR服务 (或手动运行 rapidocr_api)")
    print("2. 在界面中框选识别区域")
    print("3. 配置交易密码和参数")
    print("4. 点击'开始监控'启动")
    print("")
    print("OCR服务启动方式:")
    print("• 自动启动: 将ocr.exe放在程序目录下")
    print("• 手动启动: 运行 rapidocr_api 命令")
    print("=" * 60)


def main():
    """主函数"""
    try:
        # 显示启动信息
        show_startup_info()
        
        # 检查运行环境
        if not check_environment():
            print("\n❌ 环境检查失败，程序无法启动")
            input("按回车键退出...")
            sys.exit(1)
        
        # 初始化日志系统
        if not initialize_logging():
            print("\n❌ 日志系统初始化失败")
            input("按回车键退出...")
            sys.exit(1)
        
        # 尝试启动OCR服务
        start_ocr_service()
        
        # 检查OCR服务状态
        if not check_ocr_service():
            print("💡 提示: 如需OCR功能，请手动启动OCR服务:")
            print("   方式1: 运行 rapidocr_api")
            print("   方式2: 将ocr.exe放到程序目录下自动启动")
        
        print("\n🚀 启动图形界面...")
        print("提示: 如果界面未显示，请检查是否有防火墙或安全软件阻止")
        
        # 启动GUI应用
        try:
            gui_main()
        except Exception as gui_error:
            print(f"❌ GUI启动失败: {gui_error}")
            
            # 如果是Qt插件问题，提供解决建议
            if "platform plugin" in str(gui_error).lower():
                print("\n📝 这是虚拟环境中常见的Qt平台插件问题")
                print("解决方案:")
                print("1. 重新安装PyQt5: pip uninstall PyQt5 && pip install PyQt5")
                print("2. 或者使用conda: conda install pyqt")
                print("3. 或者退出虚拟环境，在系统Python中运行")
            
            raise gui_error
        
    except KeyboardInterrupt:
        print("\n\n👋 用户手动退出程序")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 程序启动失败: {e}")
        print("\n错误详情:")
        import traceback
        traceback.print_exc()
        input("\n按回车键退出...")
        sys.exit(1)


if __name__ == "__main__":
    main()
